package com.learning.servlet2x.response;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * ClassName: DownloadServlet
 * Description: 文件下载 Servlet
 * 1、配置web.xml
 * 2、调用(PostMan) http://localhost:8080/downloadServlet
 * <p>
 * Date: 2014-9-27 13:25 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 注意中文的文件名文件下载时，注意编码 URLEncoder
        String realPath = this.getServletContext().getRealPath("/downLoad/下载.jpg");
        System.out.println("文件的绝对路径： " + realPath);

        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        System.out.println("文件的名称为： " + fileName);

        //设置浏览器下载,文件名称是中文，需要编码
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        // 固定输出
        InputStream in = null;
        OutputStream out;
        try {
            in = new FileInputStream(realPath);
            int len;
            byte[] buffer = new byte[1024];
            out = response.getOutputStream();
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                }

            }
        }
    }

    /**
     * 使用 commons-io 实现文件下载
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 注意中文的文件名文件下载时，注意编码 URLEncoder
        String realPath = this.getServletContext().getRealPath("/downLoad/下载.jpg");
        System.out.println("文件的绝对路径： " + realPath);

        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        System.out.println("文件的名称为： " + fileName);

        //设置浏览器下载,文件名称是中文，需要编码
        resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        byte[] bytes = IOUtils.toByteArray(new FileInputStream(realPath));
        IOUtils.write(bytes, resp.getOutputStream());
    }

    /**
     * SpringMVC 的下载可以这样简单
     * @return
     * @throws Exception
     */
    /*@RequestMapping(value = "import", method = RequestMethod.GET)
    public ResponseEntity<byte[]> upload() throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "dict.txt");
        return new ResponseEntity<>(FileUtils.readFileToByteArray(new File("C:/Users/Administrator/Desktop/a.txt")), headers, HttpStatus.CREATED);
    }*/
}
